package com.example.permissionservice.service;

import com.myprojects.common.pojo.UserWithRole;
import com.myprojects.common.dto.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginService {

    @Autowired
    UserWithRoleService userWithRoleService;

    @Autowired
    UserRoleRelationService userRoleRelationService;

    @Autowired
    UserTokenService userTokenService;

    /**
     * 该方法用于使用用户信息来登录
     */
    public Msg loginByUser(UserWithRole user, BindingResult bindingResult) {
        Msg result = new Msg();//尝试登录后的返回结果
        UserWithRole dbUser = null;

        Msg msg = null;

        //先检查用户信息有没有错误
        Map<String, Object> errorMap = this.checkLoginUser(user, bindingResult);
        System.out.println(errorMap);

        //如果有误，则不可以继续尝试登录
        if (errorMap.size() >= 1) {
            result.setCode(400);
            result.setMsg("用户名或密码格式不正确!");
            result.addData("errorMap", errorMap);
            return result;
        }

        try {//尝试通过用户名来获取该用户
            dbUser = userWithRoleService.selectByUsername(user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果userDB为null，则可以准备退出了
        if (dbUser == null) {
            result.setCode(401);
            result.setMsg("该用户不存在!");
            return result;
        }

        //如果还不用返回，则继续判断密码是否正确
        //如果密码正确，则可以设置登录成功userDB.getPassword().equals(user.getPassword())
        if (userWithRoleService.matchPassword(user.getPassword(), dbUser.getEncrypt_password())) {
            result.setCode(200);
            result.setMsg("即将进行页面跳转");
            dbUser.setPassword(null);//密码设置为null
            dbUser.setEncrypt_password(null);
            String accessToken = userTokenService.setUserToken(dbUser);
            if (accessToken != null) {
//                result.addData("user", dbUser);
                result.addData("accessToken", accessToken);
                return result;
            } else {
                result.setCode(401);
                result.setMsg("生成用户token出现异常!");
            }

        } else {
            result.setCode(401);
            result.setMsg("密码错误!");
            return result;
        }
        return result;
    }

    /**
     * 该方法会通过用户名检查该用户的所有属性是否合法，给注册用户使用
     *
     * @return 携带错误信息的map，若map.size()>0则说明验证失败
     */
    public Map<String, Object> checkLoginUser(UserWithRole user, BindingResult result) {
        Map<String, Object> errorMap = new HashMap<>();

        //先检查数据格式是否有误
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors) {
                errorMap.put(error.getField(), error.getDefaultMessage());
            }
        }
        //移除没必要的错误
        errorMap.remove("nickname");
        errorMap.remove("password2");
        errorMap.remove("email");
        //返回errorMap
        return errorMap;
    }

    /**
     * 该方法用于使用用户token来注销登录
     */
    public boolean logoutByToken(String accessToken) {
        return userTokenService.deleteUserByTokenString(accessToken);
    }

}
